package models

import (
	"encoding/json"
	"errors"
	"github.com/labstack/gommon/log"
	"net/http"
	"net/url"
	"quiz/common"
	"quiz/conf"
	"time"
)

func requestToken() (token string, err error) {
	//尝试从缓存中获取Token
	err = conf.Getcc(common.Redis_AccessTokenKey, &token)
	if err != nil {
		log.Info("获取缓存中Token失败!", err)
		return "", err
	}
	//如果token不存在则继续
	u, err := url.Parse(common.TokenUrl)
	if err != nil {
		log.Info(err)
	}
	if token != "" {
		return token, nil
	}
	//如果token不存在则请求Token
	paras := &url.Values{}
	//设置请求参数
	paras.Set("appid", common.Appid)
	paras.Set("secret", common.Secret)
	paras.Set("grant_type", "client_credential")
	u.RawQuery = paras.Encode()
	resp, err := http.Get(u.String())
	//关闭资源
	if resp != nil && resp.Body != nil {
		defer resp.Body.Close()
	}
	if err != nil {
		return "", errors.New("request token err :" + err.Error())
	}

	jMap := make(map[string]interface{})
	err = json.NewDecoder(resp.Body).Decode(&jMap)
	if err != nil {
		return "", errors.New("request token response json parse err :" + err.Error())
	}

	if jMap["errcode"] == nil || jMap["errcode"] == 0 {
		accessToken, _ := jMap["access_token"].(string)
		//保存Token到redis
		conf.Setcc(common.Redis_AccessTokenKey, accessToken, -1)
		return accessToken, nil
	} else {
		//返回错误信息
		errcode := jMap["errcode"].(string)
		errmsg := jMap["errmsg"].(string)
		err = errors.New(errcode + ":" + errmsg)
		return "", err
	}

}

//7000秒刷新一次Token确保可用
func InitToken() {
	freshTokenTicker := time.NewTicker(7000 * time.Second)
	//requestToken()
	go func() {
		select {
		case <-freshTokenTicker.C:
			{
				accessToken, err := requestToken()
				if err != nil {
					log.Info("刷新Token异常!", err)
				}
				log.Printf("token refresh :%s", accessToken)
				//保存到缓存
				conf.Setcc(common.Redis_AccessTokenKey, accessToken, -1)

			}
		}
	}()

}
